package com.example.himalaya.presenters;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.interfaces.IPlayerCallback;
import com.example.himalaya.interfaces.IPlayerPresenter;
import com.example.himalaya.utils.LogUtils;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis;
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.advertis.IXmAdsStatusListener;
import com.ximalaya.ting.android.opensdk.player.constants.PlayerConstants;
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException;

import java.util.ArrayList;
import java.util.List;

import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;

public class PlayerPresenter implements IPlayerPresenter, IXmAdsStatusListener, IXmPlayerStatusListener {

    // 列表播放 PLAY_MODEL_LIST---》
    // 列表循环 PLAY_MODEL_LIST_LOOP---》
    // 随机播放 PLAY_MODEL_RANDOM ---》
    // 单曲播放 PLAY_MODEL_SINGLE---》
    // 单曲循环 PLAY_MODEL_SINGLE_LOOP
    private static final int PLAY_MODEL_LIST_INT = 0;
    private static final int PLAY_MODEL_LIST_LOOP_INT = 1;
    private static final int PLAY_MODEL_RANDOM_INT = 2;
    private static final int PLAY_MODEL_SINGLE_INT = 3;
    private static final int PLAY_MODEL_SINGLE_LOOP_INT = 4;

    //sp`s key&name
    private static final String PLAY_MODE_SP_NAME = "PlayMode";
    private static final String PLAY_MODE_SP_KEY = "currentPlayMode";


    private List<IPlayerCallback> mIPlayerCallbacks = new ArrayList<>();
    private final XmPlayerManager mXmPlayerManager;
    private String TAG = "PlayerPresenter";
    private Track mTrack;
    private List<Track> mPlayList;
    private int mIndex = 0;
    private final Context mContext;
    private final SharedPreferences mSharedPreferences;
    private XmPlayListControl.PlayMode mCurrentPlayMode = PLAY_MODEL_LIST;


    private PlayerPresenter() {
        mXmPlayerManager = XmPlayerManager.getInstance(BaseApplication.getAppContext());

        //广告相关的接口
        mXmPlayerManager.addAdsStatusListener(this);

        //注册播放器状态相关的接口
        mXmPlayerManager.addPlayerStatusListener(this);

        //需要记录播放模式
        mContext = BaseApplication.getAppContext();
        mSharedPreferences = mContext.getSharedPreferences(PLAY_MODE_SP_NAME, Context.MODE_PRIVATE);

    }

    private static PlayerPresenter mPlayerPresenter;

    public static PlayerPresenter getPlayerPresenter() {
        if (mPlayerPresenter == null) {
            synchronized (PlayerPresenter.class) {
                if (mPlayerPresenter == null) {
                    mPlayerPresenter = new PlayerPresenter();
                }
            }
        }
        return mPlayerPresenter;
    }

    private boolean isPlayListSet = false;

    public void setPlayList(List<Track> list, int playIndex) {
        if (mXmPlayerManager != null) {
            mXmPlayerManager.setPlayList(list, playIndex);
            isPlayListSet = true;
            mIndex = playIndex;
            mTrack = list.get(playIndex);
//            LogUtils.d(TAG, "title*****************"+mTrackTitle);
        } else {
//            LogUtils.d(TAG, "NOT get mXmPlayerManager");
        }

    }

    @Override
    public void play() {
        LogUtils.d(TAG, "Play");
        if (isPlayListSet) {
            mXmPlayerManager.play();
        }
    }

    @Override
    public void pause() {
        if (isPlayListSet) {
            mXmPlayerManager.pause();
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public void playPre() {
        if (mXmPlayerManager != null) {

            mXmPlayerManager.playPre();
        }
    }

    @Override
    public void playNext() {
        if (mXmPlayerManager != null) {

            mXmPlayerManager.playNext();
        }
    }

    //切换播放模式
    @Override
    public void switchPlayMode(XmPlayListControl.PlayMode mode) {
        if (mXmPlayerManager != null) {
            mCurrentPlayMode = mode;
            mXmPlayerManager.setPlayMode(mode);
            //通知UI更新播放模式
            for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
                iPlayerCallback.onPlayModeChange(mode);
            }
            //保存到SP中
            SharedPreferences.Editor edit = mSharedPreferences.edit();
            edit.putInt(PLAY_MODE_SP_KEY, getIntByPlayMode(mode));
            edit.commit();
        }

    }

    private int getIntByPlayMode(XmPlayListControl.PlayMode mode) {

        switch (mode) {
            case PLAY_MODEL_LIST:
                return PLAY_MODEL_LIST_INT;
            case PLAY_MODEL_SINGLE:
                return PLAY_MODEL_SINGLE_INT;
            case PLAY_MODEL_RANDOM:
                return PLAY_MODEL_RANDOM_INT;
            case PLAY_MODEL_LIST_LOOP:
                return PLAY_MODEL_LIST_LOOP_INT;
            case PLAY_MODEL_SINGLE_LOOP:
                return PLAY_MODEL_SINGLE_LOOP_INT;
            default:
                return PLAY_MODEL_LIST_INT;
        }
    }

    private XmPlayListControl.PlayMode getPlayModeByInt(int id) {

        switch (id) {
            case PLAY_MODEL_LIST_INT:
                return PLAY_MODEL_LIST;
            case PLAY_MODEL_SINGLE_INT:
                return PLAY_MODEL_SINGLE;
            case PLAY_MODEL_RANDOM_INT:
                return PLAY_MODEL_RANDOM;
            case PLAY_MODEL_LIST_LOOP_INT:
                return PLAY_MODEL_LIST_LOOP;
            case PLAY_MODEL_SINGLE_LOOP_INT:
                return PLAY_MODEL_SINGLE_LOOP;
            default:
                return PLAY_MODEL_LIST;
        }
    }

    @Override
    public void getPlayList() {
        if (mXmPlayerManager != null) {

            mPlayList = mXmPlayerManager.getPlayList();
            for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
                iPlayerCallback.onListLoaded(mPlayList);
            }
        }

//        mXmPlayerManager.g
    }

    @Override
    public void playByIndex(int index) {
        mXmPlayerManager.play(index);

    }

    @Override
    public void seekTo(int progress) {
//更新播放器的进度
        mXmPlayerManager.seekTo(progress);
    }

    @Override
    public boolean isPlay() {
//返回当前是否正在播放
        return mXmPlayerManager.isPlaying();
    }

    @Override
    public void registerViewCallback(IPlayerCallback iPlayerCallback) {
        iPlayerCallback.onTrackUpdate(mTrack, mIndex);

        int modeId = mSharedPreferences.getInt(PLAY_MODE_SP_KEY, PLAY_MODEL_LIST_INT);
        mCurrentPlayMode = getPlayModeByInt(modeId);
        iPlayerCallback.onPlayModeChange(mCurrentPlayMode);
        if (mIPlayerCallbacks != null) {
            if (!mIPlayerCallbacks.contains(iPlayerCallback)) {
                mIPlayerCallbacks.add(iPlayerCallback);
            }
        }
    }

    @Override
    public void unRegisterViewCallback(IPlayerCallback iPlayerCallback) {
        if (mIPlayerCallbacks != null) {
            if (mIPlayerCallbacks.contains(iPlayerCallback)) {
                mIPlayerCallbacks.remove(iPlayerCallback);
            }
        }
    }


    //******************************广告相关回调方法*******************************
    @Override
    public void onStartGetAdsInfo() {
        LogUtils.d(TAG, "onStartGetAdsInfo");
    }

    @Override
    public void onGetAdsInfo(AdvertisList advertisList) {
        LogUtils.d(TAG, "onGetAdsInfo");
    }

    @Override
    public void onAdsStartBuffering() {
        LogUtils.d(TAG, "onAdsStartBuffering");
    }

    @Override
    public void onAdsStopBuffering() {
        LogUtils.d(TAG, "onAdsStopBuffering");
    }

    @Override
    public void onStartPlayAds(Advertis advertis, int i) {
        LogUtils.d(TAG, "onStartPlayAds");
    }

    @Override
    public void onCompletePlayAds() {
        LogUtils.d(TAG, "onCompletePlayAds");
    }

    @Override
    public void onError(int what, int extra) {
        LogUtils.d(TAG, "onError  what =>" + what + "extra =>" + extra);
    }
    //******************************广告相关回调方法*******************************

    //******************************注册播放器状态相关的方法*************************
    @Override
    public void onPlayStart() {
        LogUtils.d(TAG, "onPlayStart...");
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onPlayerStart();
        }
    }

    @Override
    public void onPlayPause() {
        LogUtils.d(TAG, "onPlayPause...");
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onPlayPause();
        }
    }

    @Override
    public void onPlayStop() {
        LogUtils.d(TAG, "onPlayStop...");
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onPlayStop();
        }
    }

    @Override
    public void onSoundPlayComplete() {
        LogUtils.d(TAG, "onSoundPlayComplete...");
    }

    @Override
    public void onSoundPrepared() {
        LogUtils.d(TAG, "onSoundPrepared...");
        LogUtils.d(TAG, "current status--->" + mXmPlayerManager.getPlayerStatus());
        mXmPlayerManager.setPlayMode(mCurrentPlayMode);
        if (mXmPlayerManager.getPlayerStatus() == PlayerConstants.STATE_PREPARED) {
            mXmPlayerManager.play();
        }
    }

    //切换歌曲调用
    @Override
    public void onSoundSwitch(PlayableModel lastModel, PlayableModel currentModel) {
        if (lastModel != null) {
            LogUtils.d(TAG, "lastModel..." + lastModel.getKind());
        }
        LogUtils.d(TAG, "onSoundSwitch...");
        //currentModel代表的是当前播放的内容
        //通过getKind()方法来获取他是什么类型
        //track表示是track类型
        //第一种写法:(不推荐)
//        if("track".equals(currentModel.getKind())){
//            Track currentTrack=(Track) currentModel;
//            LogUtils.d(TAG,"title-----"+currentTrack.getTrackTitle());
//        }
        //第二种：
        if (currentModel instanceof Track) {
            LogUtils.d(TAG, "currentModel..." + currentModel.getKind());
            Track currentTrack = (Track) currentModel;
            mTrack = currentTrack;
            mIndex = mXmPlayerManager.getCurrentIndex();
//            LogUtils.d(TAG,"title-----"+currentTrack.getTrackTitle());
            for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
                iPlayerCallback.onTrackUpdate(mTrack, mIndex);
            }
        }

    }

    @Override
    public void onBufferingStart() {
        LogUtils.d(TAG, "onBufferingStart...");
    }

    @Override
    public void onBufferingStop() {
        LogUtils.d(TAG, "onBufferingStop...");
    }

    @Override
    public void onBufferProgress(int progress) {
        LogUtils.d(TAG, "onBufferProgress--" + progress);
    }

    //单位毫秒
    //交给UI处理
    @Override
    public void onPlayProgress(int current, int duration) {
        LogUtils.d(TAG, "onPlayProgress....current:--->" + current + "   duration--->" + duration);
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onProgressChange(current, duration);
        }
    }

    @Override
    public boolean onError(XmPlayerException e) {
        LogUtils.d(TAG, "e----> " + e);
        return false;
    }
    //******************************注册播放器状态相关的方法*************************

}
